package com.java;

import java.io.IOException;
import javax.servlet.http.*;

/*
 * Copyright (c) 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Management;
import com.google.api.services.analytics.Analytics.Management.Accounts;
import com.google.api.services.analytics.Analytics.Management.Webproperties;
import com.google.api.services.analytics.model.Account;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.GaData.ColumnHeaders;
import com.google.api.services.analytics.model.Profile;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperty;
import com.google.api.services.urlshortener.Urlshortener;
import com.google.api.services.urlshortener.model.Url;
import com.google.api.services.urlshortener.model.UrlHistory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Google Calendar Data API App Engine sample.
 * 
 * @author Yaniv Inbar
 */

public class AbcdServlet extends AbstractAppEngineAuthorizationCodeServlet {

	static final String APP_NAME = "Google Calendar Data API Sample Web Client";

	static final String GWT_MODULE_NAME = "calendar";

	private static final long serialVersionUID = 1L;
	private static void printGaData(GaData results) {
	    System.out.println(
	        "printing results for profile: " + results.getProfileInfo().getProfileName());

	    if (results.getRows() == null || results.getRows().isEmpty()) {
	      System.out.println("No results Found.");
	    } else {

	      // Print column headers.
	      for (ColumnHeaders header : results.getColumnHeaders()) {
	        System.out.printf("%30s", header.getName());
	      }
	      System.out.println();

	      // Print actual data.
	      for (List<String> row : results.getRows()) {
	        for (String column : row) {
	          System.out.printf("%30s", column);
	        }
	        System.out.println();
	      }

	      System.out.println();
	    }
	    }

	@Override
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		
		
//		Urlshortener shortener =  Utils.loadCalendarClient();
//		
//		UrlHistory history = shortener.url().list().execute();
//		response.setContentType("text/html");
//	    
//	    writer.append("<html><body><form action=\"/abcd\" method=\"post\">Long Url: "
//	        + "<input name=\"longUrl\" type=\"text\" /><input type=\"submit\" /></form><table><tr>"
//	        + "<th>Original</th><th>Shortened</th></tr>");
//	    if (history.getItems() != null) {
//	      for (Url oneShortened : history.getItems()) {
//	        writer.append("<tr><td>");
//	        writer.append(oneShortened.getLongUrl()).append("</td><td><a href=\"").append(
//	            oneShortened.getId());
//	        writer.append("\">").append(oneShortened.getId());
//	        writer.append("</a></td></tr>");
//	      }
//	    }
//	    writer.append("</table></body></html>");
//	    writer.flush();
		Analytics analytic = Utils.loadCalendarClient();
		Management management = analytic.management();
		
		 
				   //Analytics.Profiles.List request = analytics.profiles().list()
		 
		List<Account> accounts = management.accounts().list().execute().getItems()  ;
		for (Account account : accounts) {
			
			List<Webproperty> webproperties =management.webproperties().list(account.getId()).execute().getItems() ;
			for (Webproperty webproperty : webproperties) {
				
				System.err.println(account.getId()+":"+webproperty.getId());
				Profiles profileList  =management.profiles().list(account.getId(), webproperty.getId()).execute();
				 if (profileList.getItems()==null||profileList.getItems().isEmpty()) {
			          System.err.println("No profiles found");
			        } else {
			         String profileId = profileList.getItems().get(0).getId();
			         
			         System.out.println(profileId);
			         
						
					GaData data = 	analytic.data().ga()
				        .get("ga:"+profileId,                  // Table Id.
				            "2012-11-01",              // Start date.
				            "2012-12-14",              // End date.
				            "ga:visits")               // Metrics.
				        .setDimensions("ga:source,ga:keyword")
				        .setSort("-ga:visits,ga:source")
				        .setFilters("ga:medium==organic")
				        .setMaxResults(25)
				        .execute();
					printGaData(data);
			        }

				
				


//				for (Profile profile : profileList) {
//					System.out.println(profile);
//				}
			}
			
		}
		
		//List<Profile> profileList  =management.profiles().list(accounts.get(0).getId(), webproperties.get(0).getId()).execute().getItems();
		//System.out.println();
		
		 
		
		
		  // Print Account
	}

	@Override
	protected String getRedirectUri(HttpServletRequest req)
			throws ServletException, IOException {
		return Utils.getRedirectUri(req);
	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws IOException {
		return Utils.newFlow();
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	   
	  }
}